package com.club.football.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.club.football.common.UserHolder;
import com.club.football.dto.NewsSaveDto;
import com.club.football.dto.PageDto;
import com.club.football.entity.News;
import com.club.football.mapper.NewsMapper;
import com.club.football.req.NewsPageReq;
import com.club.football.service.NewsService;
import com.club.football.utils.BeanUtils;
import com.club.football.utils.FileUtils;
import com.club.football.utils.R;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.club.football.common.CommonConstants.*;

/**
 * 资讯服务实现
 *
 * @author 1
 * @date 2024/01/09
 */
@Service
public class NewsServiceImpl extends ServiceImpl<NewsMapper, News> implements NewsService {
    @Override
    public R<PageDto<News>> newsPage(PageDto<News> pageDto, NewsPageReq newsPageReq) {
        lambdaQuery().like(StringUtils.isNotBlank(newsPageReq.getTitle()), News::getTitle, newsPageReq.getTitle())
                .orderByDesc(News::getCreateTime).page(pageDto);
        List<News> records = pageDto.getRecords();
        if (CollUtil.isNotEmpty(records)) {
            records.forEach(item -> item.setImage(FileUtils.getUrl(item.getImage())));
        }
        return R.ok(pageDto, GET_INFO_OK);
    }

    @Override
    public R<String> newsSave(NewsSaveDto saveDto) {
        News news = BeanUtils.copier(saveDto, new News());
        Long userId = UserHolder.getUser().getUserId();
        news.setUpdateBy(userId);
        String image = saveDto.getImage();
        if (news.getNewsId() != null) {
            if (StringUtils.isBlank(image)) {
                news.setImage(getById(saveDto.getNewsId()).getImage());
            }
            updateById(news);
            return R.ok(EDIT_OK_MSG);
        }
        if (StringUtils.isBlank(image)) {
            news.setImage(FileUtils.getImageUrl(DEFAULT_IMAGE));
        }
        news.setCreateBy(userId);
        save(news);
        return R.ok(SAVE_OK_MSG);
    }
}
